import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
class TaskController {
	def authenticateService
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
		
		
        if(params.search_key){
            def taskInstanceList = Task.findAll("from Task where name like '%"+params.search_key+"%' or " +
              "description like '%"+params.search_key+"%' "
            )
            if (taskInstanceList) {
                flash.message = "Found data."
            } else {
                flash.message = "Search Not found."
            }
            [taskInstanceList: taskInstanceList, , taskInstanceTotal: taskInstanceList.count()]
        }else {
			def authPrincipal = authenticateService.principal()
			def person = User.findByUsername(authPrincipal.username)
			if (person.authorities.toArray()[0].id == Role.findByAuthority("ROLE_ADMIN").id) {
	            params.max = Math.min(params.max ? params.int('max') : 10, 100)
	            [taskInstanceList: Task.list(params), taskInstanceTotal: Task.count()]
	        }else {
				def task = person.projectTeams.project.tasks
				def taskList = []
				for(t in task){
					for(u in t){
						for(w in u){
							println "w = "+w
							taskList.add(w)
						}
					}
				}
				params.max = Math.min(params.max ? params.int('max') : 10, 100)
				[taskInstanceList:taskList, taskInstanceTotal: task.count()]
			}
        }
    }

    def create = {
		Calendar cal = Calendar.getInstance();
        def taskInstance = new Task()
        taskInstance.properties = params
		taskInstance.startDate = cal.getTime()
		cal.add(Calendar.DATE, 6)
		taskInstance.endDate = cal.getTime()
		cal.add(Calendar.DATE, 1)
		taskInstance.endPlanDate = cal.getTime()
		//def phaseList = ["PSP0","PSP0.1","PSP1","PSP1.1","PSP2","PSP2.1"]
		def phaseList = CH.config.genericPSPTypes
        return [taskInstance: taskInstance, phaseList:phaseList]
    }

    def save = {
		boolean pspAssignment = false
        def taskInstance = new Task(params)
		if (taskInstance.name == ''){
			taskInstance.name = params['psp_task_name']
			pspAssignment = true
		}
		
        if (taskInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'task.label', default: 'Task'), taskInstance.id])}"
			if(pspAssignment){
				def subTaskList = CH.config.defaultSubTask1
				if(taskInstance.name == 'PSP2' || taskInstance.name == 'PSP2.1'){
					subTaskList = CH.config.defaultSubTask2
				}
				for(subtask in subTaskList){
					def subTask = new SubTask()
					subTask.phaseName = subtask
					subTask.task = Task.get(taskInstance.id)
					subTask.save(flush: true)
				}				
			}	
			redirect(action: "show", id: taskInstance.id)
        }
        else {
            render(view: "create", model: [taskInstance: taskInstance])
        }
    }

    def show = {
        def taskInstance = Task.get(params.id)
        if (!taskInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'task.label', default: 'Task'), params.id])}"
            redirect(action: "list")
        }
        else {
            [taskInstance: taskInstance]
        }
    }

    def edit = {
        def taskInstance = Task.get(params.id)
        if (!taskInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'task.label', default: 'Task'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [taskInstance: taskInstance]
        }
    }

    def update = {
        def taskInstance = Task.get(params.id)
        if (taskInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (taskInstance.version > version) {
                    
                    taskInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'task.label', default: 'Task')] as Object[], "Another user has updated this Task while you were editing")
                    render(view: "edit", model: [taskInstance: taskInstance])
                    return
                }
            }
            taskInstance.properties = params
            if (!taskInstance.hasErrors() && taskInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'task.label', default: 'Task'), taskInstance.id])}"
                redirect(action: "show", id: taskInstance.id)
            }
            else {
                render(view: "edit", model: [taskInstance: taskInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'task.label', default: 'Task'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def taskInstance = Task.get(params.id)
        if (taskInstance) {
            try {
                taskInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'task.label', default: 'Task'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'task.label', default: 'Task'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'task.label', default: 'Task'), params.id])}"
            redirect(action: "list")
        }
    }
}
